
#include "buffer.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define JC_VORONOI_IMPLEMENTATION
// If you wish to use doubles
//#define JCV_REAL_TYPE double
//#define JCV_FABS fabs
//#define JCV_ATAN2 atan2
//#define JCV_CEIL ceil
//#define JCV_FLOOR floor
//#define JCV_FLT_MAX 1.7976931348623157E+308
#include "jc_voronoi.h"

#define INIT_MEM 8

double *calculate_cluster(double *data, double distance)
{
    // Output will go here
    Buffer buf;
    initBuffer(&buf);
    buf.buf_push(&buf, 0); // total number of doubles in buffer
    buf.buf_push(&buf, 0); // number of cells

    size_t pos = 0;


  jcv_rect rect;
  rect.min.x = rect.min.y = JCV_FLT_MAX;
  rect.max.x = rect.max.y = -JCV_FLT_MAX;


  int i;
  jcv_rect bounding_box = { { 0.0f, 0.0f }, { 1.0f, 1.0f } };
  jcv_diagram diagram;
  jcv_graphedge* graph_edge;

  memset(&diagram, 0, sizeof(jcv_diagram));

  srand(0);

  size_t nPoints = (size_t)data[pos++];
  jcv_point* points = (jcv_point*)malloc( sizeof(jcv_point) * nPoints );
  for (size_t i = 0; i < nPoints; ++i)
  {
      points[i].id = (int)data[pos++];
      points[i].x = ((float)data[pos++]);
      points[i].y = ((float)data[pos++]);
      jcv_rect_union(&rect, &points[i]);
  }


  jcv_diagram_generate(nPoints, points, &rect, 0, &diagram, distance);
  const jcv_site* sites = jcv_diagram_get_sites( &diagram );
  size_t nParticles = 0;
  for( int i = 0; i < diagram.numsites; ++i )
  {
      const jcv_site* site = &sites[i];
      jcv_point s = site->p;
      buf.buf_push(&buf, (double)site->index);
      buf.buf_push(&buf, (double)s.x);
      buf.buf_push(&buf, (double)s.y);
      buf.buf_push(&buf, (double)site->count);
      buf.buf_push(&buf, (double)site->parent);
      ++nParticles;
  }

    jcv_diagram_free( &diagram );

    buf.set_at(&buf, 1, (double)nParticles);
    buf.set_at(&buf, 0, (double)buf.pos);
    return (double*)buf.buf;
}



